import axiosInstance from './axiosInstance';

/**
 * 认证相关API
 */
const authApi = {
  /**
   * 用户登录
   * @param {Object} credentials - 登录凭证
   * @param {string} credentials.username - 用户名
   * @param {string} credentials.password - 密码
   * @returns {Promise<Object>} 登录响应数据
   */
  login: async (credentials) => {
    try {
      const response = await axiosInstance.post('/auth/login', credentials);
      
      // 保存token和用户信息到localStorage
      // 由于axiosInstance的响应拦截器返回response.data，所以我们直接从response中获取数据
      let token = response.token || response.access_token || response.data?.token || response.data?.access_token;
      let userData = response.user || response.data?.user;
      
      if (token) {
        localStorage.setItem('token', token);
      }
      if (userData) {
        localStorage.setItem('user', JSON.stringify(userData));
      }
      
      return response;
    } catch (error) {
      console.error('登录失败:', error);
      // 清理可能存在的不完整认证信息
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      throw error;
    }
  },

  /**
   * 用户注册
   * @param {Object} userData - 用户注册数据
   * @returns {Promise<Object>} 注册响应数据
   */
  register: async (userData) => {
    try {
      const response = await axiosInstance.post('/auth/register', userData);
      return response;
    } catch (error) {
      console.error('注册失败:', error);
      throw error;
    }
  },

  /**
   * 检查用户是否已登录
   * @returns {boolean} 是否已登录
   */
  isLoggedIn: () => {
    return !!localStorage.getItem('token');
  },

  /**
   * 获取当前登录用户信息
   * @returns {Object|null} 用户信息对象或null
   */
  getCurrentUser: () => {
    const userStr = localStorage.getItem('user');
    return userStr ? JSON.parse(userStr) : null;
  },

  /**
   * 用户登出
   */
  logout: () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
  }
};

export default authApi;